import React from 'react'
import {connect} from 'react-redux'
import MovieOverview from 'components/MovieOverview'
import {
  fetchFilmDetail,
  shortCommentChange,
  submitComment,
  escape
} from 'actions/filmDetail'

class FilmDetail extends React.Component {
  render() {
    let {title, director, imgUrl, casts, desc
      , writingComment} = this.props
    return (
      <div className="container-home">
        <MovieOverview
          title={title}
          director={director}
          imgUrl={imgUrl}
          casts={casts}
          desc={desc}
        />
        <input
          placeholder='请输入影片短评'
          // 输入框的value属性绑定到了组件从仓库状态映射过来的属性上，
          // 所以这是一个受控组件
          value={writingComment.text}
          onChange={this.commentChangeHandler.bind(this)}
          // 输入框的背景色通过writingComment.exceed状态来控制，
          // 以警告字数超限
          style={{
            background: writingComment.exceed ? 'yellow' : ''
          }}
        />
        <button
          disabled={!writingComment.text}
          onClick={this.commentSubmitHandler.bind(this)}>
          发表评论
        </button>
        <ul className="comment-list">
          {this.props.commentList.map(item =>
            <li key={item.get('id')} className="comment-item">
              <span className="time">
                {item.get('time')}
              </span>
              <span className="content">
                {item.get('content')}
              </span>
            </li>
          )}
        </ul>
      </div>
    );
  }
  commentChangeHandler(event){
    this.props.dispatch(shortCommentChange(event.target.value))
  }
  commentSubmitHandler(){
    const time = new Date()
    const {text, exceed} = this.props.writingComment
    if(exceed){
      window.alert('评论字数超限')
    }else{
      this.props.dispatch(submitComment(time, text))
    }
  }
  componentDidMount() {
    this.props.dispatch(fetchFilmDetail('e08a137971b4a9a5'))
  }
  componentWillUnmount() {
    this.props.dispatch(escape())
  }
}

function mapStateToProps(state) {
  return {
    title: state.filmDetail.info.title,
    director: state.filmDetail.info.director,
    imgUrl: state.filmDetail.info.imgUrl,
    casts: state.filmDetail.info.casts,
    desc: state.filmDetail.info.desc,
    commentList: state.filmDetail.commentList,
    writingComment: state.filmDetail.writingComment
  }
}

export default connect(mapStateToProps)(FilmDetail);
